package org.neuedu.service.impl;

import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.neuedu.entity.Lzwfile;
import org.neuedu.service.FileUploadService;
import org.neuedu.service.LzwfileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${minio.url}")
    String url;
    @Value("${minio.password}")
    String password;

    @Value("${minio.username}")
    String username;

    @Resource
    LzwfileService lzwfileService;
    @Override
    public String upload(MultipartFile file, String bucket) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        long size=file.getSize();
        String type=file.getContentType();
        String md5= DigestUtils.md5Hex(file.getInputStream());

        Lzwfile lzwfile=lzwfileService.get(md5,size,type);
        if(null !=lzwfile){
            return lzwfile.getPath();
        }

        String rename=String.format("%s.%s",NanoIdUtils.randomNanoId(), FilenameUtils.getExtension(file.getOriginalFilename()));
        MinioClient client=MinioClient.builder()
                .endpoint(url)
                .credentials(username,password)
                .build();
        PutObjectArgs argsg=PutObjectArgs.builder()
                .object(rename)
                .contentType(type)
                .bucket(bucket)
                .stream(file.getInputStream(),size,0)
                .build();
        client.putObject(argsg);
        String path=String.format("/%s/%s",bucket,rename);
        lzwfile=new Lzwfile(null,md5,size,type,path);
        lzwfileService.save(lzwfile);
        return path;
    }
}
